<template>
  <div class="discussion-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="discussion-header">
          <h1>课程讨论区</h1>
          <p>在这里您可以与同学和老师交流课程相关问题和想法</p>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="mt-20">
      <el-col :xs="24" :sm="6" :md="6" :lg="6">
        <el-card class="discussion-sidebar">
          <div class="sidebar-header">
            <h3>讨论分类</h3>
          </div>
          <el-menu
            :default-active="activeCategory"
            class="category-menu"
            @select="handleCategorySelect"
          >
            <el-menu-item index="all">
              <el-icon><Document /></el-icon>
              <span>全部讨论</span>
            </el-menu-item>
            <el-menu-item index="announcement">
              <el-icon><Bell /></el-icon>
              <span>课程公告</span>
            </el-menu-item>
            <el-menu-item index="question">
              <el-icon><QuestionFilled /></el-icon>
              <span>问题求助</span>
            </el-menu-item>
            <el-menu-item index="resource">
              <el-icon><Folder /></el-icon>
              <span>资源共享</span>
            </el-menu-item>
            <el-menu-item index="experience">
              <el-icon><ChatLineRound /></el-icon>
              <span>学习心得</span>
            </el-menu-item>
          </el-menu>
          
          <div class="course-filter mt-20">
            <h3>按课程筛选</h3>
            <el-select v-model="selectedCourse" placeholder="选择课程" class="w-100">
              <el-option
                v-for="course in courses"
                :key="course.id"
                :label="course.name"
                :value="course.id"
              />
            </el-select>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="18" :md="18" :lg="18">
        <el-card class="discussion-content">
          <div class="content-header">
            <div class="header-title">
              <h2>{{ categoryTitle }}</h2>
            </div>
            <div class="header-actions">
              <el-button type="primary" @click="showPostDialog = true">
                <el-icon><Plus /></el-icon> 发布新帖子
              </el-button>
            </div>
          </div>
          
          <el-tabs v-model="activeTab" class="mt-20">
            <el-tab-pane label="最新发布" name="latest"></el-tab-pane>
            <el-tab-pane label="热门讨论" name="hot"></el-tab-pane>
            <el-tab-pane label="我的发布" name="mine"></el-tab-pane>
          </el-tabs>
          
          <div class="post-list mt-20">
            <div v-if="posts.length === 0" class="empty-posts">
              <el-empty description="暂无相关帖子" />
            </div>
            
            <div v-else class="post-items">
              <el-card v-for="post in posts" :key="post.id" class="post-item" shadow="hover">
                <div class="post-header">
                  <div class="user-info">
                    <el-avatar :size="40" :src="post.author.avatar"></el-avatar>
                    <div class="user-details">
                      <span class="username">{{ post.author.name }}</span>
                      <span class="post-time">{{ formatDate(post.createTime) }}</span>
                    </div>
                  </div>
                  <el-tag size="small" :type="getTagType(post.category)">
                    {{ getCategoryName(post.category) }}
                  </el-tag>
                </div>
                
                <div class="post-title" @click="viewPostDetail(post.id)">
                  <h3>{{ post.title }}</h3>
                </div>
                
                <div class="post-summary">
                  {{ post.summary }}
                </div>
                
                <div class="post-footer">
                  <span class="post-stats">
                    <el-icon><View /></el-icon> {{ post.views }} 浏览
                  </span>
                  <span class="post-stats">
                    <el-icon><ChatDotRound /></el-icon> {{ post.comments }} 评论
                  </span>
                  <span class="post-stats">
                    <el-icon><Star /></el-icon> {{ post.likes }} 赞
                  </span>
                </div>
              </el-card>
            </div>
            
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 发布帖子对话框 -->
    <el-dialog
      v-model="showPostDialog"
      title="发布新帖子"
      width="700px"
    >
      <el-form :model="postForm" label-width="80px">
        <el-form-item label="标题" required>
          <el-input v-model="postForm.title" placeholder="请输入帖子标题" />
        </el-form-item>
        <el-form-item label="类别" required>
          <el-select v-model="postForm.category" placeholder="请选择帖子类别">
            <el-option label="课程公告" value="announcement" />
            <el-option label="问题求助" value="question" />
            <el-option label="资源共享" value="resource" />
            <el-option label="学习心得" value="experience" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联课程">
          <el-select v-model="postForm.courseId" placeholder="选择相关课程">
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input
            v-model="postForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入帖子内容"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="https://api.example.com/upload"
            multiple
            :limit="3"
            :file-list="postForm.fileList"
          >
            <el-button type="primary">上传附件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传文档、图片等文件，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPostDialog = false">取消</el-button>
          <el-button type="primary" @click="submitPost">发布</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Document, Bell, QuestionFilled, Folder, ChatLineRound, Plus, View, ChatDotRound, Star } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 状态定义
const activeCategory = ref('all')
const selectedCourse = ref('')
const activeTab = ref('latest')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showPostDialog = ref(false)

// 表单数据
const postForm = ref({
  title: '',
  category: '',
  courseId: '',
  content: '',
  fileList: []
})

// 模拟数据
const courses = ref([
  { id: 1, name: '数据结构与算法' },
  { id: 2, name: '计算机网络' },
  { id: 3, name: '操作系统' },
  { id: 4, name: '软件工程' }
])

const posts = ref([
  {
    id: 1,
    title: '关于数据结构期末考试的通知',
    summary: '本学期数据结构课程将于下周三进行期末考试，考试内容包括链表、树、图等，请同学们做好复习准备。',
    author: { name: '张教授', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
    category: 'announcement',
    courseId: 1,
    createTime: '2023-12-20T08:30:00',
    views: 245,
    comments: 18,
    likes: 32
  },
  {
    id: 2,
    title: '求助：二叉树遍历算法实现问题',
    summary: '在实现二叉树的后序遍历时遇到了一些问题，特别是在处理空节点时程序会崩溃，有没有同学可以帮忙看一下？',
    author: { name: '小明', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
    category: 'question',
    courseId: 1,
    createTime: '2023-12-19T15:20:00',
    views: 120,
    comments: 8,
    likes: 5
  },
  {
    id: 3,
    title: '分享：计算机网络经典教材PDF',
    summary: '整理了一些计算机网络的经典教材和学习资料，包括《计算机网络：自顶向下方法》等，希望对大家有帮助。',
    author: { name: '小红', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' },
    category: 'resource',
    courseId: 2,
    createTime: '2023-12-18T10:15:00',
    views: 356,
    comments: 25,
    likes: 48
  }
])

// 计算属性
const categoryTitle = computed(() => {
  switch (activeCategory.value) {
    case 'all': return '全部讨论'
    case 'announcement': return '课程公告'
    case 'question': return '问题求助'
    case 'resource': return '资源共享'
    case 'experience': return '学习心得'
    default: return '全部讨论'
  }
})

// 方法
const handleCategorySelect = (key) => {
  activeCategory.value = key
  // 重新加载帖子数据
  loadPosts()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadPosts()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadPosts()
}

const loadPosts = () => {
  // 这里应该调用API获取数据
  // 暂时使用模拟数据
  total.value = posts.value.length
  
  // 筛选逻辑
  let filteredPosts = [...posts.value]
  
  if (activeCategory.value !== 'all') {
    filteredPosts = filteredPosts.filter(post => post.category === activeCategory.value)
  }
  
  if (selectedCourse.value) {
    filteredPosts = filteredPosts.filter(post => post.courseId === selectedCourse.value)
  }
  
  // 根据选项卡筛选
  if (activeTab.value === 'mine') {
    // 筛选当前用户的帖子 (实际应用中需要获取用户ID)
    // filteredPosts = filteredPosts.filter(post => post.author.id === currentUser.id)
  } else if (activeTab.value === 'hot') {
    // 按热度排序
    filteredPosts.sort((a, b) => b.views - a.views)
  } else {
    // 最新发布，按时间排序
    filteredPosts.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
  }
  
  total.value = filteredPosts.length
  posts.value = filteredPosts
}

const viewPostDetail = (postId) => {
  // 查看帖子详情
  console.log('查看帖子:', postId)
  // 这里应该跳转到帖子详情页面
}

const submitPost = () => {
  // 提交帖子
  if (!postForm.value.title || !postForm.value.category || !postForm.value.content) {
    ElMessage.warning('请填写必填项')
    return
  }
  
  // 模拟提交成功
  ElMessage.success('发布成功')
  showPostDialog.value = false
  
  // 重置表单
  postForm.value = {
    title: '',
    category: '',
    courseId: '',
    content: '',
    fileList: []
  }
  
  // 重新加载数据
  loadPosts()
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
}

const getTagType = (category) => {
  switch (category) {
    case 'announcement': return 'danger'
    case 'question': return 'warning'
    case 'resource': return 'success'
    case 'experience': return 'info'
    default: return ''
  }
}

const getCategoryName = (category) => {
  switch (category) {
    case 'announcement': return '公告'
    case 'question': return '问题'
    case 'resource': return '资源'
    case 'experience': return '心得'
    default: return '其他'
  }
}

onMounted(() => {
  loadPosts()
})
</script>

<style scoped>
.discussion-container {
  padding: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.w-100 {
  width: 100%;
}

.discussion-header {
  text-align: center;
  background-color: #f0f6ff;
}

.discussion-header h1 {
  margin-bottom: 10px;
  color: #409eff;
}

.discussion-sidebar {
  margin-bottom: 20px;
}

.sidebar-header {
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.course-filter {
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.post-list {
  margin-top: 20px;
}

.post-item {
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.post-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 10px;
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: bold;
  font-size: 14px;
}

.post-time {
  font-size: 12px;
  color: #909399;
}

.post-title {
  margin: 10px 0;
}

.post-title h3 {
  margin: 0;
  color: #303133;
}

.post-summary {
  color: #606266;
  margin-bottom: 15px;
  line-height: 1.5;
}

.post-footer {
  display: flex;
  color: #909399;
  font-size: 13px;
}

.post-stats {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.post-stats .el-icon {
  margin-right: 5px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.empty-posts {
  padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
  }
}
</style> 